﻿using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Security;
using Sustainalytics.LongRunningTaskManager.Interface;
using System;
using System.Diagnostics;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Sustainalytics.LongRunningTaskManager.Service
{
    [Authorize]
    public class LongRunningTaskHub : Hub
    {
        private readonly LongRunningTaskManagerHostConfiguration _config;

        private readonly LongRunningTaskHubManager _hubManager;

        /// <summary>
        /// Ctor.
        /// </summary>
        public LongRunningTaskHub()
            : this(LongRunningTaskHubManager.Instance, LongRunningTaskManagerHostConfiguration.Current) 
        { }

        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="hubManager"> Hub manager. </param>
        public LongRunningTaskHub(LongRunningTaskHubManager hubManager, LongRunningTaskManagerHostConfiguration config)
        {
            this._hubManager = hubManager;
            this._config = config;
        }


        public override Task OnConnected()
        {
            Task ret;
            try
            {
                var ticket = GetAuthenticationTicket();

                if (Context.User.Identity.IsAuthenticated)
                    _hubManager.AddUserConnection(ticket, Context.ConnectionId);
            }
            catch (Exception ex) { }
            finally
            {
                ret = base.OnConnected();
            }

            return ret;
        }

        public override Task OnReconnected()
        {
            Task ret;
            try
            {
                var ticket = GetAuthenticationTicket();

                if (Context.User.Identity.IsAuthenticated)
                    _hubManager.AddUserConnection(ticket, Context.ConnectionId);
            }
            catch (Exception ex) { }
            finally
            {
                ret = base.OnReconnected();
            }

            return ret;
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            Task ret;
            try
            {
                var ticket = GetAuthenticationTicket();

                if (Context.User.Identity.IsAuthenticated)
                    _hubManager.RemoveUserConnection(ticket, Context.ConnectionId);
            }
            catch (Exception ex) { }
            finally
            {
                ret = base.OnDisconnected(stopCalled);
            }

            return ret;
        }

        private AuthenticationTicket GetAuthenticationTicket()
        {
            var ticket = new AuthenticationTicket((ClaimsIdentity)Context.User.Identity, new AuthenticationProperties());
            return ticket;
        }
    }
}
